var common = require("../../common/common.js");
var server = require("../../common/server.js");
// var dateutils = require("../../../common/dateutils.js");

var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {

    productid: '0',
    orderno: '',
    storecount:0,
    count:0,
    payamount:0,
    checked:false,
    addresstotalcount: 0,//记录地址数量
    address: "",
    linkman: "",
    mobile: "",
    addressid: 0,
    used_account_money:0,
    yunPrice:0
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
    var that = this;

    var user = app.globalData.user;// || wx.getStorageSync('user');
    var company= app.globalData.currentCompany;
    that.setData({
      user: user,
      company: company
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    var memberid = app.rd_session || wx.getStorageSync('rd_session');

    that.setData({
      carnoIndex: 0,
      carno: [],
    })
    // common.getMember({
    //   app: app,
    //   that: that,
    //   memberId: memberid
    // });

    wx.getStorage({
      key: 'shopCarInfo',
      success: function (res) {
          var shopCarInfo = res.data;

          var ids = [];
          var ids = "";
          var count = 0;
          var productamount = 0;
          for (var m = 0; m < shopCarInfo.length; m++) {
            var cartgood = shopCarInfo[m];
            count += parseInt(cartgood.amount);
            productamount += parseInt(cartgood.amount) * parseFloat(cartgood.price);
            // ids.push(cartgood.id)
            ids+=cartgood.id+",";
          }
          if (ids){
            ids = ids.substring(0,ids.length-1);
          }

          var amount = productamount;
          var payamount = amount;
          //满足优惠券使用条件
          var temp_voucherAmount = 0;
          var voucherId = app.globalData['voucherId'] || '';
          var voucherAmount = 0;
          var voucherLimitAmount = app.globalData['voucherLimitAmount'] || 0;
          if (voucherId) {
            if (payamount >= voucherLimitAmount) {
              voucherAmount = app.globalData['voucherAmount'] || 0;
              temp_voucherAmount = parseFloat(voucherAmount);
            }

          }

          // //满足红包使用条件
          // var redPacketId = app.globalData['redPacketId'] || '';
          // var redPacketMoney = 0;
          // var redPacketLimitAmount = app.globalData['redPacketLimitAmount'] || 0;
          // var temp_redPacketMoney = 0;
          // if (redPacketId) {
          //   if (payamount >= redPacketLimitAmount) {
          //     redPacketMoney = app.globalData['redPacketMoney'] || 0;
          //     temp_redPacketMoney = parseFloat(redPacketMoney);
          //   }
          // }

          // if (temp_voucherAmount + temp_redPacketMoney >= productamount) {
          //   payamount = 0.01;
          // } else {
          //   payamount = payamount - temp_voucherAmount - temp_redPacketMoney;
          // }

          if (temp_voucherAmount >= productamount) {
            payamount = 0.01;
          } else {
            payamount = payamount - temp_voucherAmount;
          }

          that.setData({
            ids: ids,
            cartgoods: shopCarInfo,
            count: count,
            productamount: productamount,
            amount: amount,
            payamount: payamount
          })

          that.initPageInfo();

          
         
      }
    })
   

    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
  onShareAppMessage: function () {
  },
   */
  bindPickerChange: function (e) {
    var that = this;
    var timeselect = that.data.area;
    that.setData({
      areaIndex: e.detail.value
    })

  },
  bindDayPickerChange: function (e) {
    var that = this;
    var day = that.data.day;
    that.setData({
      dayIndex: e.detail.value
    })

    that.setServiceTime();

  },
  bindCarmodelPickerChange: function (e) {
    var that = this;
    //var carmodelIndex = that.data.carmodel;
    this.setData({
      carmodelIndex: e.detail.value
    })

  }, 
  bindCarnoPickerChange: function (e) {
    var that = this;
    //var carnoIndex = that.data.carno;
    if (that.data.carno[e.detail.value]=='新增车辆'){
      wx.navigateTo({
        url: '/page/mine/car/detail',
      })
    }else{
      this.setData({
        carnoIndex: e.detail.value
      })
    }
    
  },

  
  ringUp: function (e) {
    var phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  
  messageInput: function (e) {
    this.setData({
      message: e.detail.value
    })
  },
  initPageInfo: function () {
    var that = this;

    
    that.setData({
      cur_account_money: app.globalData.user.wu_balance||'',
      base_account_money: app.globalData.user.wu_balance||''
    });



    var user = app.globalData.user;//wx.getStorageSync('selectAddress');

    if (user && user.address) {
      var address = user.address;
      that.setData({
        addresstotalcount: 1,
        address: address.wd_province + address.wd_city + address.wd_area + address.wd_town + address.wd_addr || '',
        linkman: address.wd_name || '',
        mobile: address.wd_mobile || '',
        addressid: address.wd_id || '',
        // latitude: address.latitude || '',
        // longitude: address.longitude || '',
      });
    }

    var payamount = that.data.payamount;
    var productamount = that.data.payamount;
    var amount = productamount;

    //满足优惠券使用条件
    var voucherId = app.globalData['voucherId'] || '';
    var voucherAmount = 0;
    
    var voucherLimitAmount = app.globalData['voucherLimitAmount'] || 0;
    if (voucherId) {
      if (payamount >= voucherLimitAmount) {
        voucherAmount = app.globalData['voucherAmount'] || 0;
      }
    }

    
    if (voucherAmount >= productamount ){
      payamount = 0;
    }else{
      payamount = productamount - voucherAmount

    }
    that.setData({
      amount: amount,
      productamount: productamount,
      payamount: payamount,
      voucherId: voucherId,
      voucherAmount: voucherAmount,
    });
  },
  navMap: function (e) {
    var latitude = parseFloat(e.target.dataset.latitude);
    var longitude = parseFloat(e.target.dataset.longitude);
    var name = e.target.dataset.name;
    //console.warn('latitude:' + latitude + ',longitude:' + longitude + ',name:' + name);
    wx.openLocation({
      latitude: latitude,
      longitude: longitude,
      name: name,
      scale: 28
    })
  },
  formSubmit: function (e) {
    var that = this;
    var openID = app.globalData.user.openid || 'wzz001';//测试用

    var hmapid = common.gb.ID;
    var id = that.data.productid;
    var count = that.data.count;
    var message = that.data.message || "";
    var addressid = that.data.addressid;
    

    if (!addressid) {
      wx.showModal({
        title: '提示',
        content: '请选择地址信息',
      })
      return false;
    }

   
   

    if(that.data.count == 0){
      wx.showToast({
        title: '还没有选择商品哦'
      })
      return false;
    }

    
    that.setData({
      openID: openID,
      message: message,
    })
    

    if (!that.data.checked && that.data.cur_account_money > 0 ) {
      wx.showModal({
        title: '温馨提示',
        content: '账户余额充足，是否需要抵扣!',
        confirmText: '好的',
        cancelText: '取消',
        success: function (e) {
          if (e.confirm) {
            that.setPayamount();
          } else {
            that.toPayOrder();
          }
        }
      })

    } else {
      that.toPayOrder();
    }
    
    
  },
  toPayOrder:function(){
    var that= this;
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    });
    //设置对应的按钮为disabled
    that.setData({
      createorderevent: true
    })


    that.setData({
      controller: '/api/wx/order/saveOrder',
      params: {
        companyid: app.globalData.currentCompany.companyid,//公司id
        shop_code: app.globalData.currentCompany.sp_code,//店铺编码
        wu_code: app.globalData.user.wu_code,
        cartids: that.data.ids,
        address: that.data.address,
        mobile: that.data.mobile,
        linkman: that.data.linkman,
        message: that.data.message,
        yunfee:0,//待定
        voucherid: that.data.voucherId,
        voucheramount: that.data.voucherAmount,
        usedaccountamount: that.data.used_account_money
      }
    })

    common.doMethod({
      that: that,
      succFun: function (data) {
        if (data) {
            if (data.data){
              wx.showToast({
                title: '订单提交成功',
                icon:'none',
                success: function (res) {
                  // //支付金额
                  var paymoney = data.data.order.paymoney;
                  //订单号
                  var ordernumber = data.data.order.ordernumber;
                  //订单说明
                  var productdesc = data.data.order.productdesc;
                  //支付时间
                  var createdate = data.data.order.createdate;


                  var paytype = data.data.paytype || '';
                  var url = data.data.url || '';
                  if (paymoney != 0) {
                    if (paytype == '2') {
                      wx.navigateTo({
                        url: '/pages/receive/receive?url=' + url + '&orderNo=' + ordernumber + '&payAmount=' + paymoney,
                      })
                    } else {
                      that.setData({
                        controller: '/api/wx/wxpay/pay',
                        params: {
                          openID: user.wu_openid,
                          paymoney: paymoney,
                          ordernumber: ordernumber,
                          productdesc: productdesc,
                          createdate: createdate
                        }
                      })

                      common.doMethod({
                        that: that,
                        succFun: function (data) {
                          that.setData({
                            createorderevent: true
                          })
                          if (res.data.ErrorCode == 0) {
                            var data = JSON.parse(res.data.Data);
                            wx.requestPayment({
                              'timeStamp': data.timeStamp,
                              'nonceStr': data.nonceStr,
                              'package': data.package,
                              'signType': 'MD5',
                              'paySign': data.paySign,
                              'success': function (res) {
                                console.warn("success");
                                wx.showToast({
                                  title: '支付成功',
                                  icon: 'loading',
                                  duration: 3000,
                                  success: function () {
                                    wx.redirectTo({
                                      url: '/pages/order/order-details/index?orderno=' + ordernumber,
                                    })
                                  }
                                })
                              },
                              'fail': function (res) {
                                console.warn("fail");
                              }
                            })
                          }
                        }
                      })
                    }
                  } else {
                    wx.showToast({
                      title: '跳转中...',
                      icon: 'none',
                      duration: 3000,
                      success: function (e) {
                        app.globalData['payTmp'] = "paied";
                        app.globalData['payStatus'] = "success";
                        wx.redirectTo({
                          url: '/pages/order/orderdetail/orderdetail?orderno=' + ordernumber,
                        })
                      }
                    })

                  }
                 
                },
              })
              
              
            }
            else {
              wx.showToast({
                title: data.data,
                icon: 'none'
              });
            }            
        }
      }
    })
  },
   showHideAllStore: function (e) {
    var that = this;
    if (that.data.isshowallstore == "block") {
      that.setData({
        isshowallstore: "none"
      })

    } else {
      that.setData({
        isshowallstore: "block"
      })
    }

  },
  linkCoupon: function (e) {
    var that = this;
    var item = that.data.item;

    var payamount = e.currentTarget.dataset.payamount;
    //var activityid = e.currentTarget.dataset.activityid;
    //var count = e.currentTarget.dataset.count;

    wx.navigateTo({
      url: "/pages/coupon/coupon?pageamount="+payamount,
      success:function(e){
        app.globalData['voucherId'] = null;
        app.globalData['voucherAmount'] = null;
      }
    });
  },
  linkRedPacket: function (e) {
    var that = this;
    var payamount = e.currentTarget.dataset.payamount;

    wx.navigateTo({
      url: '/pages/hongbao/hongbao?pageamount=' + payamount,
      success: function (e) {
        app.globalData['redPacketId'] = null;
        app.globalData['redPacketMoney'] = null;
      }
    });
  },
  setServiceTime: function (e) {
    var that = this;
    that.setData({
      areaIndex: 0,
      area: []
    })

    var curdate = that.data.curdate;
    var hour_begin = wx.getStorageSync('store') ? wx.getStorageSync('store').hourbegin : "00:00";
    var hour_end = wx.getStorageSync('store') ? wx.getStorageSync('store').hourend : "24:00";
    if (hour_end == "00:00") {
      hour_end = "24:00";
    }



    // var start = hour_begin;
    // var end = "";
    // if (parseInt(hour_begin.split(":")[0])<10){
    //   end = "0" + parseInt(hour_begin.split(":")[0]) + ":" + hour_begin.split(":")[1];
    // }else{
    //   end = (parseInt(hour_begin.split(":")[0])+1) + ":" + hour_begin.split(":")[1]
    // }
    // that.data.area.push('当日' + hour_begin + '-' + end);
    //分钟间隔
    var stopmin = 30;
    var hh = parseInt(curdate.getHours().toString().length == 1 ? "0" + curdate.getHours() : curdate.getHours());
    var i_mm = parseInt(curdate.getMinutes());

    var s_hh = hour_end.split(":")[0]
    var mm = "";
    if (i_mm > 0 && i_mm <= 30) {
      mm = "30";
    }
    else if (i_mm > 30 && i_mm <= 60) {
      mm = "00";
      //hh = hh + 1;
    }

    if (that.data.dayIndex == 0) {
      if (parseInt(hour_begin.split(":")[0]) <= hh) {
        hour_begin = (hh < 10 ? "0" + hh : hh) + ":" + mm;
      }
    } else {
      var curstr = curdate.format("yyyy-MM-dd");
      var time1str = (curstr + " " + hour_begin + ":00").replace(/-/g, "/");
      var time1 = new Date(time1str).getTime();
      var time2str = (curstr + " " + hour_end + ":00").replace(/-/g, "/");
      var time2 = new Date(time2str).getTime();
      var newdate = new Date(time1);

      hh = newdate.getHours() < 10 ? '0' + newdate.getHours() : newdate.getHours();
      var e_hh = (newdate.getHours() + 1) < 10 ? '0' + (newdate.getHours() + 1) : (newdate.getHours() + 1);
      mm = newdate.getMinutes() < 10 ? '0' + newdate.getMinutes() : newdate.getMinutes();
      var start = hh + ':' + mm;

      var end = e_hh + ':' + mm;

      that.data.area.push(start + '-' + end);
      // that.data.area.push('当日' + start + '-' + end);

    }

    var curstr = curdate.format("yyyy-MM-dd");
    var time1str = (curstr + " " + hour_begin + ":00").replace(/-/g, "/");
    var time1 = new Date(time1str).getTime();
    var time2str = (curstr + " " + hour_end + ":00").replace(/-/g, "/");
    var time2 = new Date(time2str).getTime();

    var ok = 1;
    while (ok) {
      time1 = time1 + 1000 * 60 * stopmin;
      if (time1 > time2) {
        ok = 0;
      } else {
        var newdate = new Date(time1);

        hh = newdate.getHours() < 10 ? '0' + newdate.getHours() : newdate.getHours();
        var e_hh = (newdate.getHours() + 1) < 10 ? '0' + (newdate.getHours() + 1) : (newdate.getHours() + 1);
        mm = newdate.getMinutes() < 10 ? '0' + newdate.getMinutes() : newdate.getMinutes();
        var start = hh + ':' + mm;

        var end = e_hh + ':' + mm;

        if (e_hh <= s_hh) {
          // that.data.area.push('当日' + start + '-' + end);
          that.data.area.push(start + '-' + end);
        }
        if (end == hour_end){
          break;
         }
      }
    }
    
    //that.data.area.push('当日' + start + '-' + end);

    that.setData({
      area: that.data.area,
    })
  },
  setPayamount:function(e){
    var that = this;
    var val = that.data.base_account_money;//e.currentTarget.dataset.basemoney;
    if (that.data.checked){
      that.setData({
        cur_account_money: parseFloat(val),
        used_account_money: 0,
        payamount: (parseFloat(that.data.payamount) + parseFloat(that.data.used_account_money)).toFixed(2),
      })
      that.setData({
        checked: false
      })
    }else{
      if (parseFloat(val) > 0) {
        if (parseFloat(val) <= that.data.payamount) {
          that.setData({
            cur_account_money:0,
            used_account_money: parseFloat(val),
            payamount: (parseFloat(that.data.payamount) - parseFloat(val)).toFixed(2),
          })
        } else {
          that.setData({
            cur_account_money: (parseFloat(val) - parseFloat(that.data.payamount)).toFixed(2),
            used_account_money: that.data.payamount,
            payamount: 0,
          })
        }
      }
      that.setData({
        checked: true
      })
    }
  },
  addAddress: function () {

    wx.navigateTo({
      url: "/page/mine/addressadd/addressadd?pageurl=service"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/my/address/list/list"
    })
  },
  linkcar:function(){
    wx.showModal({
      title: 'fff',
      content: 'ff',
    })
  },
  
})
function transDate() {
  var date = new Date();
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return (Y + M + D)
}
function transTime() {
  var date = new Date();
  var h = date.getHours() + ':';
  var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  return (h + m)
}
function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
  return currentdate;
}
